from tkinter import *
from tkinter.filedialog import askopenfilename
import cv2
import numpy as np

from PIL import Image, ImageTk

areas = (
    ((173, 710), (236, 239)),
    ((480, 707), (240, 239)),
    ((785, 702), (241, 237)),
    ((1092, 699), (244, 241)),
    ((1396, 698), (249, 244))
)

target_path = 'C:/Users/lenovo/Pictures/compare.jpg'

def calc_pt(pt, size):
    return pt[0] + size[0], pt[1] + size[1]


def selectPath():
    path = askopenfilename()

    # img = Image.open(path)  # 打开图片
    # photo = ImageTk.PhotoImage(img)  # 用PIL模块的PhotoImage打开

    img_data = cv2.imread(path)
    img_data1 = cv2.imread(target_path)

    for area in areas:
        cv2.rectangle(img_data, area[0], calc_pt(area[0], area[1]), (0, 255, 0), 3)
    #     compare_img(img_data, img_data1, area[0], area[1])

    cv2image = cv2.cvtColor(img_data, cv2.COLOR_BGR2RGBA)
    img = Image.fromarray(cv2image)
    photo = ImageTk.PhotoImage(img)

    # cv2.imshow("Mouth3", img_data)
    # cv2.waitKey(0)


    imglabel.configure(image=photo)
    imglabel.image = photo


def compare_img(img1, img2, pt1, size):
    """

    :rtype: int
    """
    pt2 = calc_pt(pt1, size)
    sub_img1 = np.float32(img1[pt1[1]:pt2[1], pt1[0]:pt2[0]])
    sub_img2 = np.float32(img2[pt1[1]:pt2[1], pt1[0]:pt2[0]])
    result_img = sub_img1 - sub_img2
    res = ((result_img ** 2).sum(axis=2)) > 100
    res = np.sum(res)
    print('res='+str(res)+" "+str(res/(size[0]*size[1])))
    return res


def draw_mark(img, pt):
    cv2.circle(img, pt, 63, (0, 0, 255), -1)


root = Tk()
Button(root, text="路径选择", command=selectPath).grid(row=0, column=0)
imglabel = Label(root)
imglabel.grid(row=1, column=0)

root.mainloop()
